package org.absolutezero.model;

import java.util.logging.Logger;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Version;


@Entity
@Table(name="recipe_ingredient")
public class RecipeIngredient {

	private static Logger logger = Logger.getLogger(User.class.getName());

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    
   @Version
    private Integer version;
    
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="recipe_id")
    private Recipe recipe;
    
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="product_id")
    private Product product;
    
    
    private Long  quantity;


	public Long getId() {
		return id;
	}


	public void setId(Long id) {
		this.id = id;
	}


	public Recipe getRecipe() {
		return recipe;
	}


	public void setRecipe(Recipe recipe) {
		this.recipe = recipe;
	}


	public Product getProduct() {
		return product;
	}


	public void setProduct(Product product) {
		this.product = product;
	}


	public Long getQuantity() {
		return quantity;
	}


	public void setQuantity(Long quantity) {
		this.quantity = quantity;
	}
    
	public static RecipeIngredient findRecipeIngredient(Long id){
 		if (id == null) {
 		      return null;
	    }
	    EntityManager em = entityManager();
	    try {
	      RecipeIngredient ri = em.find(RecipeIngredient.class, id);
	      return ri;
	    } finally {
	      em.close();
	    }
 	}
	
	public Integer getVersion(){
 		return version;
 	}
	
	public void setVersion(Integer version){
		this.version = version;
	}
	
	@Override
 	public String toString(){
 		return String.format("User[%d, %d, %d, %d]", id, recipe.getId(), product.getId(), quantity);
 	}
	
	 private static EntityManager entityManager(){
     	return EMF.get().createEntityManager();
     }
                     
     
     public void persist() {
     	
 	    EntityManager em = entityManager();
 	    
 	    try {
 	    	
 	      EntityTransaction tx  = em.getTransaction();
  	      tx.begin();
  	      this.product = em.merge(this.product);
  	      this.recipe = em.merge(this.recipe);
  	      logger.info("Persisting recipie_ingredient");
  	      RecipeIngredient ri  = em.merge(this);
 	      em.persist(ri);
 	      tx.commit();
 	     
 	    } finally {
 	      em.close();
 	    }
 	  }

 	public void remove() {
 	    EntityManager em = entityManager();
 	    try {
 	      RecipeIngredient attached = em.find(RecipeIngredient.class, this.id);
 	      EntityTransaction tx  = em.getTransaction();
  	      tx.begin();
 	      em.remove(attached);
 	      tx.commit();
 	    } finally {
 	      em.close();
 	    }
 	  }
	
}
